package com.cnc.common.web.oss;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;

import java.io.*;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;

/**
 * Created by c9131 on 2017-09-26.
 *
 *
 */
public class OSSFileClient implements OSSFileUpload {

    private String accessKey = "6V7a9gzzytB-iApIU3gtr4sol_5qHV4eurCaavqC";

    private String secretKey = "";

    private String bucket = "blog";

    private String downloadAddress = "http://devtools.qiniu.com";

    private String ossURL = "http://owtfq0j7q.bkt.clouddn.com";


    public OSSFileClient(String accessKey, String secretKey, String bucket, String downloadAddress, String ossURL) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucket = bucket;
        this.downloadAddress = downloadAddress;
        this.ossURL = ossURL;
    }

    @Override
    public String uploadFile(String path, String fileName, File file) throws FileNotFoundException {
        if (null == fileName || "".equals(fileName)) {
            fileName = file.getName();
        }
        return uploadFile(path, fileName, file.length(), new FileInputStream(file));
    }

    @Override
    public String uploadFile(String path, String fileName, long contentLength, InputStream fileData) {
        if(contentLength > 5368709120L) {throw new IllegalArgumentException("内容长度不能超过5G字节。");}
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
//...其他参数参考类注释

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = getKey(path,fileName);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        //System.getenv("java.io.tmpdir") java 临时路径
        String localTempDir = Paths.get(path, bucket).toString();
        try {
            //设置断点续传文件进度保存目录
            FileRecorder fileRecorder = new FileRecorder(localTempDir);
            UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
            try {
                Response response = uploadManager.put(fileData, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(key);
                System.out.println(putRet.hash);
                return putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return "";
    }
    public  String getKey(String path, String fileName) {
        String key = "";
        if (null != path && !"".equals(path)) {
            while (path.startsWith("/") || path.startsWith("\\")) {
                path = path.substring(1);//取相对路径
            }
            if (!path.endsWith("/")) {
                path += "/";
            }
            key += path;
        }
        key += fileName;
        return key;
    }
    @Override
    public String getAddress(String key) {
        //String.format()
        return "";
    }

    @Override
    public void downloadFile(String key, File fileDownloadPath) {
//        String fileName = "七牛/云存储/qiniu.jpg";
//        String domainOfBucket = "http://devtools.qiniu.com";
//        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
//        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
//        String accessKey = "your access key";
//        String secretKey = "your secret key";
//        Auth auth = Auth.create(accessKey, secretKey);
//        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
//        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
//        System.out.println(finalUrl);
    }

    @Override
    public FileContent downloadFile(String key) {
        return null;
    }

    @Override
    public List<String> listFile(String path) {
        return null;
    }


}
